﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Transactions;
using System.Net;
using System.ComponentModel;
using System.Threading;
using EntityFrameworks.Data.Core;
using Common.Background.Helper;
using DynamicProxy.IInterceptor;
using System.IO;
using EntityFrameworks.Entity.Core.CommonEnums;
using Project.Messaging;

namespace Common.Background.Controllers
{
    public partial class SystemController : BaseController
    {
        public SystemController()
            : base(new backgroundEntities())
        {

        }

        #region 系统初始化
        public ActionResult Index()
        {
            if (UserRepository.GetModel().Count() > 0)
            {
                return RedirectToAction("LogOn", "System");
            }
            return View();
        }

        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            ViewBag.Message = "基本信息初始化完毕，请单进行<a href='/account/logon'>登陆</a>";
            DateTime createDate = DateTime.Now;
            #region 部门信息，角色信息，用户信息
            if (DeptRepository.Find(1) == null)
            {
                var dept = new WebDepartments
                {
                    About = string.Empty,
                    DepartmentName = form["DepartmentName"] ?? "公司",
                    Operator = string.Empty,
                    ParentID = null,
                    SortNumber = 1,
                    Status = (int)Status.Normal,
                    UpdateDate = createDate,
                    DeptLevel = 0
                };
                DeptRepository.Insert(dept);

                #region 菜单信息
                if (MenuRepository.Find(1) == null)
                {
                    var menu = new WebManageMenus
                    {
                        About = string.Empty,
                        LinkUrl = string.Empty,
                        MenuLevel = 0,
                        MenuName = form["MenuName"] ?? "根",
                        Operator = string.Empty,
                        ParentID = null,
                        SortNumber = 1,
                        Status = Status.Normal.GetHashCode(),
                        UpdateDate = createDate,
                        WebManageMenus1 = new List<WebManageMenus>
                     {
                        new WebManageMenus
                        {
                            About = string.Empty,
                            LinkUrl = string.Empty,
                            MenuLevel = 1,
                            MenuName ="系统管理",
                            Operator = string.Empty,
                            SortNumber = 1,
                            Status = Status.Normal.GetHashCode(),
                            UpdateDate =createDate,
                            WebManageMenus1 = new List<WebManageMenus>
                             {
                                #region 二级菜单
		                        new WebManageMenus
                                {
                                    About = string.Empty,
                                    LinkUrl = string.Empty,
                                    MenuLevel = 2,
                                    MenuName ="角色管理",
                                    Operator = string.Empty,
                                    SortNumber = 1,
                                    Status = Status.Normal.GetHashCode(),
                                    UpdateDate =createDate,
                                    WebManageMenus1 = new List<WebManageMenus>
                                    {
                                        new WebManageMenus
                                        {
                                            About = string.Empty,
                                            LinkUrl = "/Role/Create",
                                            MenuLevel = 3,
                                            MenuName ="新建角色",
                                            Operator = string.Empty,
                                            SortNumber = 1,
                                            Status = Status.Normal.GetHashCode(),
                                            UpdateDate = createDate
                                        },
                                        new WebManageMenus
                                        {
                                            About = string.Empty,
                                            LinkUrl = "/Role/Index",
                                            MenuLevel = 3,
                                            MenuName ="管理角色",
                                            Operator = string.Empty,
                                            SortNumber = 1,
                                            Status = Status.Normal.GetHashCode(),
                                            UpdateDate = createDate
                                        }      
                                  }
                                }, 
	                            #endregion
                                #region 二级菜单
		                        new WebManageMenus
                                {
                                    About = string.Empty,
                                    LinkUrl = string.Empty,
                                    MenuLevel = 2,
                                    MenuName ="部门管理",
                                    Operator = string.Empty,
                                    SortNumber = 1,
                                    Status = Status.Normal.GetHashCode(),
                                    UpdateDate = createDate,
                                    WebManageMenus1 = new List<WebManageMenus>
                                    {
                                        new WebManageMenus
                                        {
                                            About = string.Empty,
                                            LinkUrl = "/Department/Index",
                                            MenuLevel = 3,
                                            MenuName ="管理部门",
                                            Operator = string.Empty,
                                            SortNumber = 1,
                                            Status = Status.Normal.GetHashCode(),
                                            UpdateDate = createDate
                                        }    
                                   }
                                }, 
	                            #endregion
                                #region 二级菜单
		                        new WebManageMenus
                                {
                                    About = string.Empty,
                                    LinkUrl = string.Empty,
                                    MenuLevel = 2,
                                    MenuName ="菜单管理",
                                    Operator = string.Empty,
                                    SortNumber = 1,
                                    Status = Status.Normal.GetHashCode(),
                                    UpdateDate = createDate,
                                    WebManageMenus1 = new List<WebManageMenus>
                                    {
                                        new WebManageMenus
                                        {
                                            About = string.Empty,
                                            LinkUrl = "/Menu/Index",
                                            MenuLevel = 3,
                                            MenuName ="管理菜单管理",
                                            Operator = string.Empty,
                                            SortNumber = 1,
                                            Status = Status.Normal.GetHashCode(),
                                            UpdateDate = createDate
                                        }    
                                   }
                                }, 
	                            #endregion
                                #region 二级菜单
		                        new WebManageMenus
                                {
                                    About = string.Empty,
                                    LinkUrl = string.Empty,
                                    MenuLevel = 2,
                                    MenuName ="员工管理",
                                    Operator = string.Empty,
                                    SortNumber = 1,
                                    Status = Status.Normal.GetHashCode(),
                                    UpdateDate = createDate,
                                    WebManageMenus1 = new List<WebManageMenus>
                                    {
                                        new WebManageMenus
                                        {
                                            About = string.Empty,
                                            LinkUrl = "/WebUser/Create",
                                            MenuLevel = 3,
                                            MenuName ="新建员工",
                                            Operator = string.Empty,
                                            SortNumber = 1,
                                            Status = Status.Normal.GetHashCode(),
                                            UpdateDate = createDate
                                        },
                                        new WebManageMenus
                                        {
                                            About = string.Empty,
                                            LinkUrl = "/WebUser/Index",
                                            MenuLevel = 3,
                                            MenuName ="管理员工",
                                            Operator = string.Empty,
                                            SortNumber = 1,
                                            Status = Status.Normal.GetHashCode(),
                                            UpdateDate = createDate
                                        }      
                                  }
                                }, 
	                            #endregion
                             }
                       }
                   }
                    };
                    MenuRepository.Insert(menu);
                }
                #endregion

                #region 角色信息与用户信息
                WebManageRoles role;
                if (RoleRepository.Find(1) == null)
                {
                    role = new WebManageRoles
                    {
                        About = string.Empty,
                        DepartmentID = dept.ID,
                        Operator = string.Empty,
                        OperatorAuthority = 63,
                        RoleName = form["RoleName"] ?? "管理员",
                        SortNumber = 1,
                        Status = Status.Normal.GetHashCode(),
                        UpdateDate = createDate,
                        WebManageMenus = MenuRepository.GetModel().ToList(),
                    };
                    RoleRepository.Insert(role);

                    #region 用户信息与用户角色关系信息
                    string userName = form["UserName"];
                    string password = VCommons.Encryptor.Utility.EncryptString(form["Password"], VCommons.Encryptor.Utility.EncryptorType.MD5);
                    if (UserRepository.Find(1) == null)
                    {
                        var user = new WebManageUsers
                        {
                            DepartmentID = dept.ID,
                            CreateDate = createDate,
                            Description = string.Empty,
                            Email = string.Empty,
                            LoginName = userName,
                            Mobile = string.Empty,
                            Operator = string.Empty,
                            Password = password,
                            RealName = userName,
                            Status = (int)Status.Normal,
                            UpdateDate = createDate,
                            WebSystemID = 1,
                        };
                        user.WebManageRoles = new List<WebManageRoles> { role };
                        UserRepository.Insert(user);
                    }
                    #endregion

                }
                #endregion

            }
            #endregion




            return RedirectToAction("LogOn", "System");
        }
        #endregion

        #region 登陆与登出
        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(FormCollection form)
        {
            string userName = form["UserName"];
            string startPage = System.Configuration.ConfigurationManager.AppSettings["startPage"];
            string password = VCommons.Encryptor.Utility.EncryptString(form["Password"], VCommons.Encryptor.Utility.EncryptorType.MD5);
            try
            {
                var entity = LoadRepository<WebManageUsers>()
                                .GetModel()
                                .Include(i => i.WebManageRoles)
                                .FirstOrDefault(i => i.LoginName == userName && i.Password == password && (i.Status & (int)Status.Deleted) == 0);
                if (entity != null)
                {
                    base.CurrentUserId = entity.ManageUserID;
                    base.CurrentUserName = entity.LoginName;
                    if (entity.WebManageRoles != null && entity.WebManageRoles.Any())
                    {
                        entity.WebManageRoles.ToList().ForEach(j =>
                        {
                            base.CurrentOperatorAuthority |= j.OperatorAuthority;
                        });
                    }
                    if (!string.IsNullOrWhiteSpace(form["returnUrl"]))
                    {
                        return Redirect(form["returnUrl"]);
                    }
                    else
                    {
                        if (string.IsNullOrWhiteSpace(startPage))
                            return RedirectToAction("StartPage", "System");
                        else
                            return Redirect(startPage);
                    }
                }
                else
                {
                    ModelState.AddModelError("", "用户名密码错误");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "系统发生未知错误" + ex.Message);
            }

            return View();
        }

        public ActionResult LogOff()
        {
            Session.Clear();
            return RedirectToAction("Index", "System");
        }
        #endregion

        /// <summary>
        /// 起始页
        /// </summary>
        /// <returns></returns>
        [Common.Background.Filter.AuthorizationFilter]
        public ActionResult StartPage()
        {
            return View();
        }
    }
}

